package com.ivy.parser.utils.number;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigNumberUtil {

    private volatile static BigNumberUtil instance;

    private BigNumberUtil(){}

    public static BigNumberUtil NEW(){
        if(instance == null){
            synchronized (BigNumberUtil.class){
                if(instance == null){
                    instance = new BigNumberUtil();
                }
            }
        }
        return instance;
    }


    public String add(String n1, String n2) {
        NumberInfo numberInfo1 = NumberInfo.NEW(n1);
        NumberInfo numberInfo2 = NumberInfo.NEW(n2);
        int diff = Integer.parseInt(numberInfo1.getE()) - Integer.parseInt(numberInfo2.getE());
        if (Math.abs(diff) > 2) {
            return diff > 0 ? n1 : n2;
        }
        if(diff > 0){
            return add(numberInfo1,numberInfo2);
        }else{
            return add(numberInfo2,numberInfo1);
        }
    }

//    public String subtract(String n1, String n2) {
//        NumberInfo numberInfo1 = NumberInfo.NEW(n1);
//        NumberInfo numberInfo2 = NumberInfo.NEW(n2);
//        int diff = Integer.parseInt(numberInfo1.getE()) - Integer.parseInt(numberInfo2.getE());
//        if (Math.abs(diff) > 2) {
//            return diff > 0 ? n1 : n2;
//        }
//        if(diff > 0){
//            return subtract(numberInfo1,numberInfo2);
//        }else{
//            return subtract(numberInfo2,numberInfo1);
//        }
//    }

    private String add(NumberInfo numberInfo1,NumberInfo numberInfo2){
        BigDecimal b1 = new BigDecimal(numberInfo1.getN());
        BigDecimal b2 = new BigDecimal(numberInfo2.getN());
        b2 = b2.divide(BigDecimal.valueOf(10),2, RoundingMode.DOWN);
        b1 = b1.add(b2).setScale(2, RoundingMode.DOWN);
        return b1.toString() + "e" + numberInfo1.getE();
    }

//    private String subtract(NumberInfo numberInfo1,NumberInfo numberInfo2){
//        BigDecimal b1 = new BigDecimal(numberInfo1.getN());
//        BigDecimal b2 = new BigDecimal(numberInfo2.getN());
//        b2 = b2.divide(BigDecimal.valueOf(10),2, RoundingMode.DOWN);
//        b1 = b1.subtract(b2).setScale(2, RoundingMode.DOWN);
//        return b1.toString() + "e" + numberInfo1.getE();
//    }
}
